import Vue from 'vue'

const findNodeById = (id, treeData) => {
  for (let node of treeData) {
    if (node.id === id) {
      return node
    }
    if (node.children) {
      let found = findNodeById(id, node.children)
      if (found) return found
    }
  }
  return null
}

export const addNodeToChildren = (parentId, isLeaf, treeData, newNode) => {
  let parentNode = findNodeById(parentId, treeData)
  if (parentNode) {
    if (!parentNode.hasOwnProperty('children')) {
      Vue.set(parentNode, 'children', [])
    }
    parentNode.children.push(newNode)
  } else {
    throw new Error('找不到父节点')
  }
}

// 修改节点配置项
export const updateNode = (parentId, treeData, newNode, isLeaf) => {
  let currentNode = findNodeById(parentId, treeData)
  currentNode.label = newNode.label
  currentNode.tip = newNode.tip
  currentNode.weight = newNode.weight
  if (isLeaf) {
    currentNode.attributes = newNode.attributes
  }
}

// 校验树权重,返回对应节点的id
export const checkTreeWeight = (node, parentId = null) => {
  // 提取当前节点的直接子节点
  const children = node.children || []
  // 计算当前层级所有节点的 weight 之和
  if (children.length > 0) {
    const weightSum = children.reduce((sum, child) => sum + child.weight, 0)
    // 检查 weight 之和是否等于 100
    if (weightSum !== 100) {
      // 如果不等于 100，返回当前层级的父节点 ID  
      return parentId
    }
  }
  // 递归检查每一层子节点
  for (const child of children) {  
    const invalidParentId = checkTreeWeight(child, child.id)
    if (invalidParentId) {
      return invalidParentId
    }  
  }
  // 如果所有层级都有效，返回 null 表示没有错误  
  return null
}  